package com.gidgabs.modules.api.controller;

import com.gidgabs.common.annotation.LoginUserApi;
import com.gidgabs.common.utils.*;
import com.gidgabs.common.validator.Assert;
import com.gidgabs.dto.TbShoppingCarDto;
import com.gidgabs.modules.api.service.TbProductService;
import com.gidgabs.modules.api.service.TbShoppingCarService;
import com.gidgabs.modules.api.service.TbUserService;
import com.gidgabs.modules.entity.TbProductEntity;
import com.gidgabs.modules.entity.TbShoppingCarEntity;
import com.gidgabs.modules.entity.TbUser;
import com.gidgabs.utils.SessionDataUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * 购物车表
 *
 * @author lanyonglin
 * @email www.baidu.com
 * @date 2018-07-02 10:07:07
 */
@Api("购物车模块")
@RestController
@RequestMapping("/api/shoppingcar")
public class TbShoppingCarController {

    @Autowired
    private TbShoppingCarService shoppingCarService;

    @Autowired
    private TbProductService tbProductService;

    @Autowired
    private TbUserService userService;

    /**
     * 查询我的购物车列表（分页）
     *
     * @param pageSize
     * @param pageNo
     * @return
     */
    @ApiOperation(value = "查询我的购物车列表（分页）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageSize", value = "页面大小", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageNo", value = "页码", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "string", paramType = "header")
    })
    @GetMapping("/myCar")
    public ReturnJson<TbShoppingCarDto> myCar(Integer pageSize, Integer pageNo) {
        //获取用户信息
        TbUser tbUser = new TbUser();
        tbUser.setUserId(SessionDataUtil.getCurrentUserId());
        TbUser user = userService.queryObject(tbUser);
        if (user == null) {
            return ReturnJson.fail("登录用户不存在！");
        }
        if (pageNo == null) {
            pageNo = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        return shoppingCarService.queryShoppingCarList(pageSize, pageNo, user.getUserId());
    }

    /**
     * 添加产品至购物车
     *
     * @param productId
     * @param amount
     * @return
     */
    @ApiOperation(value = "添加产品至购物车")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productId", value = "产品id", dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "amount", value = "数量", dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "string", paramType = "header")
    })
    @PostMapping("/save")
    public ReturnJson<TbShoppingCarEntity> save(Integer productId, Integer amount) {
        //获取用户信息
        TbUser tbUser = new TbUser();
        tbUser.setUserId(SessionDataUtil.getCurrentUserId());
        TbUser user = userService.queryObject(tbUser);
        if (user == null) {
            return ReturnJson.fail("登录用户不存在！");
        }
        Assert.isNull(productId, "参数不能为空");
        Assert.isNull(amount, "参数不能为空");
        //查询产品
        TbProductEntity tbProductEntity = tbProductService.selectTbProductById(productId);
        if (tbProductEntity == null) {
            return ReturnJson.fail("产品不存在");
        }
        //查询购物车中是否存在产品
        TbShoppingCarEntity shoppingCarEntity = new TbShoppingCarEntity();
        shoppingCarEntity.setProductId(productId);
        shoppingCarEntity.setUserId(user.getUserId());
        TbShoppingCarEntity shoppingCar = shoppingCarService.selectTbShoppingCarObjSingle(shoppingCarEntity);
        //如果购物车存在产品 就修改数量
        if (shoppingCar != null) {
            //数量=原数量+1
            shoppingCar.setAmount(shoppingCar.getAmount() + 1);
            shoppingCarService.updateNotNullTbShoppingCarById(shoppingCar);
            return ReturnJson.success("操作成功");
        }
        TbShoppingCarEntity tbShoppingCarEntity = new TbShoppingCarEntity();
        tbShoppingCarEntity.setUserId(user.getUserId());
        tbShoppingCarEntity.setProductId(productId);
        tbShoppingCarEntity.setAmount(amount);
        tbShoppingCarEntity.setGraphicIntroductionUrl(tbProductEntity.getGraphicIntroductionUrl());
        tbShoppingCarEntity.setPrice(tbProductEntity.getPrice());
        tbShoppingCarEntity.setProductName(tbProductEntity.getProductName());
        tbShoppingCarEntity.setCreateTime(new Date());
        tbShoppingCarEntity.setProductMasterId(tbProductEntity.getUserId());
        shoppingCarService.save(tbShoppingCarEntity);
        return ReturnJson.success("操作成功");
    }

    /**
     * 购物车产品数量加或者减
     *
     * @param productId
     * @param signType
     * @return
     */
    @PostMapping("/addOrSubTractNumber")
    @ApiOperation("购物车产品数量加或者减")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "购物车数据id", dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "signType", value = "产品数量加减标识 1 为加 2为减", dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "string", paramType = "header")
    })
    public ReturnJson<TbShoppingCarEntity> addOrSubTractNumber(Integer id, Integer signType) {
        //获取用户信息
        TbUser tbUser = new TbUser();
        tbUser.setUserId(SessionDataUtil.getCurrentUserId());
        TbUser user = userService.queryObject(tbUser);
        if (user == null) {
            return ReturnJson.fail("登录用户不存在！");
        }
        Assert.isNull(id, "参数不能为空");
        //查询购物车中是否存在产品
        TbShoppingCarEntity shoppingCarEntity = new TbShoppingCarEntity();
        shoppingCarEntity.setId(id);
        TbShoppingCarEntity shoppingCar = shoppingCarService.selectTbShoppingCarObjSingle(shoppingCarEntity);
        if (shoppingCar == null) {
            return ReturnJson.fail("产品不存在了");
        }
        //判断是加还是减
        //加算
        if (signType == 1) {
            //数量=原数量+1
            shoppingCar.setAmount(shoppingCar.getAmount() + 1);
            shoppingCarService.updateNotNullTbShoppingCarById(shoppingCar);
        }
        //减算
        else if (signType == 2) {
            //减去后的数量
            int amount = shoppingCar.getAmount() - 1;
            //如果数量减为0了 就删除该产品 反之就修改数量
            if (amount <= 0) {
                Integer[] ids = new Integer[1];
                ids[0] = id;
                shoppingCarService.deleteBatch(ids);
            } else {
                shoppingCar.setAmount(amount);
                shoppingCarService.updateNotNullTbShoppingCarById(shoppingCar);
            }
        } else {
            return ReturnJson.fail("操作失败 参数有误");
        }
        return ReturnJson.success("操作成功");
    }

    /**
     * 删除购物车产品
     *
     * @param ids
     * @return
     */
    @PostMapping("/delete")
    @ApiOperation("删除购物车产品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "id集", dataType = "int", paramType = "form"),
            @ApiImplicitParam(name = "token", value = "token", dataType = "string", paramType = "header")
    })
    public ReturnJson<TbShoppingCarEntity> delete(Integer[] ids) {
        Assert.isNull(ids, "参数不能为空");
        shoppingCarService.deleteBatch(ids);
        return ReturnJson.success("操作成功");
    }
}
